<template>
  <div class="change-password-container">
    <el-card class="password-card">
      <el-form
          :model="pwdForm"
          :rules="rules"
          ref="pwdFormRef"
          label-width="120px"
          class="password-form"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
              v-model="pwdForm.oldPassword"
              type="password"
              show-password
              placeholder="请输入原密码"
          ></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="pwdForm.newPassword"
              type="password"
              placeholder="请输入新密码(6-20位字符)"
          ></el-input>
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
              v-model="pwdForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
              type="success"
              @click="submitPwd"
              style="width: 120px; margin-left: 300px;"
              :loading="loading"
          >
            确认修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import axios from 'axios';

const router = useRouter();
const pwdFormRef = ref(null);
const loading = ref(false);

const pwdForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else if (value.length < 6 || value.length > 20) {
    callback(new Error('密码长度应为6-20位'));
  } else {
    if (pwdForm.value.confirmPassword !== '') {
      pwdFormRef.value.validateField('confirmPassword');
    }
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== pwdForm.value.newPassword) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

const rules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ]
};

const user = ref(getUser());
const submitPwd = () => {
  pwdFormRef.value.validate(valid => {
    if (!valid) return;

    if (pwdForm.value.oldPassword === pwdForm.value.newPassword) {
      ElMessage.warning('新密码不能与原密码相同');
      return;
    }

    loading.value = true;

    axios.post('http://localhost:8080/v1/user/changePassword', {
      id: user.value.id,
      password: pwdForm.value.newPassword,
      username: user.value.username,
      role: user.value.role,
      phone: user.value.phone
    })
        .then(response => {
          if (response.data.code == 2000) {
            ElMessageBox.confirm('密码修改成功，请重新登录').then(() => {
              localStorage.removeItem('user');
              router.push('/log');
            }).catch(() => {

            });
          } else {
            ElMessage.error(response.data.msg || '密码修改失败');
          }
        })
        .catch(error => {
          ElMessage.error('密码修改失败');
          console.error(error);
        })
        .finally(() => {
          loading.value = false;
        });
  });
};

</script>

<style scoped>
.change-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f6f6f6;
}

.password-card {
  width: 600px;
  padding: 30px;
  margin-top: 50px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.password-form {
  margin-top: 20px;
}

.back-link {
  text-align: center;
  margin-top: 20px;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}
</style>